import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
import { select, Store } from "@ngrx/store"
import { fromEvent, Observable } from "rxjs"
import { filter, map } from 'rxjs/operators'
import { AppState } from "./store"
import { addTodo, delTodo } from "./store/actions/counter.actions"
import { Todo } from './store/reducers/counter.reducer';
import { selectTodo , selectTodos } from "./store/selectors/counter.selectors"
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styles: []
})
export class AppComponent implements AfterViewInit {
  title = 'angular-test';
  todos: Observable<Todo[]>
  @ViewChild('AddTodoInput') AddTodoInput!:ElementRef
  constructor(private store: Store<AppState>) {
    this.todos = this.store.pipe(select(selectTodos))
  }
  
  ngAfterViewInit() {
    fromEvent<KeyboardEvent>(this.AddTodoInput.nativeElement ,'keyup')
    .pipe(
      filter(event => event.key === 'Enter'),
      map(event => (<HTMLInputElement>event.target).value),
      map(title => title.trim()),
      filter(title => title !== '')
      )
    .subscribe((title) => {
      this.store.dispatch(addTodo({title}))
      this.AddTodoInput.nativeElement.value = ''
    })
  }

  
  delTodo(id:string) {
    console.log(id)
    this.store.dispatch(delTodo({id}))
    // this.store.dispatch(delTodo())
  }
}
